import React, { Component } from 'react';
import {
    Button, Form, Radio, Checkbox, Input, Select, Icon, message,Cascader
} from 'antd';
import styles from './index.less';
import { connect } from 'dva';
import router from 'umi/router';
import InputText from '@/components/Input/index';

// const AMap = window.AMap;

@connect(({global, address}) => ({
    oemInfo: global.oemInfo,
    address
}))

class EditAddress extends React.Component {
    constructor() {
        super();
        this.state ={
            btnLoading: false,
            addressList: [],
            choiceItem: [],
            initialData: {}
        }
    }

    componentDidMount() {
        this.getBaseAddress();
        this.getStoreAddress();
        // const map = new window.AMap.Map(this.mapContainer, {
        //     resizeEnable: true,
        //     center: [116.403322, 39.900255], // 地图中心点
        //     zoom: 13 // 地图显示的缩放级别
        // });
        // this.map =map;
        // map.plugin(['AMap.ToolBar', 'AMap.MouseTool', 'AMap.PolyEditor'], () => {
        //     map.addControl(new window.AMap.ToolBar());
        //   });
        //   // // 在地图中添加MouseTool插件
        //   const mouseTool = new window.AMap.MouseTool(map);
        //   //    点击绘制按钮
        //   // AMap.event.addDomListener(this.polygon, 'click', () => {
        //   //   this.map.clearMap();
        //   mouseTool.polygon();
        //   // }, false);
        //   //    捕获坐标路径
        //   AMap.event.addListener(
        //     mouseTool,
        //     'draw',
        //     e => {
        //       // 添加事件
        //       this.setState({
        //         path: e.obj.getPath()
        //       });
        //       this.map.clearMap();
        //       editor._polygon = this.drawPolygon(e.obj.getPath());
        //       editor._polygonEditor = new AMap.PolyEditor(this.map, editor._polygon);
        //       editor._polygonEditor.open();
        //       this.map.setFitView();
        //     },
        //     false
        //   );
    }

    // 获取地址
    getBaseAddress =() => {
        const { dispatch } = this.props;
        dispatch({
            type: 'address/GetBaseAddress',
            callBack: {
                success: res => {
                    if(res.Code ===0) {
                        this.setState({
                            addressList: res.Data
                        })
                    }
                },
                error: res => {
                    message.error(res.Msg);
                }
            }
        })
    }

    //Id获取数据
    getStoreAddress=() => {
        let { dispatch, match } = this.props;
        let Id = match.params.id;
        dispatch({
            type: 'address/GetStoreAddress',
            payload: {
                Id: Id
            },
            callBack: {
                success: res => {
                    if(res.Code ===0){
                        this.setState({
                            initialData: res.Data,
                            choiceItem: [{label:res.Data.ProvName},{label:res.Data.CityName},{label:res.Data.DistrictName}]
                        })
                    }
                },
                error: res => {
                    message.error(res.Msg);
                }
            }
        })
    }

    addressTransform = (arr,arr2,parentIndex,childIndex) =>{
        let newArr=arr2||[];
        if(arr){
            for(let i=0;i<arr.length;i++){
                let item=arr[i];
                newArr.push({
                    value:item.Id,
                    label:item.Name,
                    children:[]
                });
                if(item.HasChild){
                    for(let j=0;j<item.Child.length;j++){
                        let item2=arr[i].Child[j];
                        newArr[i].children.push({
                            value:item2.Id,
                            label:item2.Name,
                            children:[]
                        })
                        if(item2.HasChild&&item2.Child.length>0){
                            for(let k=0;k<item2.Child.length;k++){
                                let item3=arr[i].Child[j].Child[k];
                                newArr[i].children[j].children.push({
                                    value:item3.Id,
                                    label:item3.Name,
                                });
                            }
                        }
                    }
                }
            }
        }
        return newArr;
    }

    onChangeCascader =(value, select) => {
        this.setState({
            choiceItem: select
        })
    }

    handleSubmit =(e) => {
        e.preventDefault();
        this.props.form.validateFieldsAndScroll((err, values) => {
            if(!err) {
                this.setState({ btnLoading: true });
                const {dispatch, match} = this.props;
                let Id = match.params.id;
                dispatch({
                    type: 'address/UpdateStoreAddress',
                    payload: {
                        Id: Id,
                        ContractName: values.name,
                        ContractPhone: values.phone,
                        ProvId: values.area[0],
                        ProvName: this.state.choiceItem[0].label,
                        CityId: values.area[1],
                        CityName: this.state.choiceItem[1].label,
                        DistrictId: values.area[2]?values.area[2]:values.area[1],
                        DistrictName: this.state.choiceItem[2]&&this.state.choiceItem[2].label?
                              this.state.choiceItem[2].label:this.state.choiceItem[1].label,
                        // DistrictId: values.area[2],
                        // DistrictName: this.state.choiceItem[2].label,
                        AddressDetail: values.detail,
                        Lng: 0, //经度
                        Lat: 0, // 纬度
                        ZipCode: values.zipCode,
                        IsDefaultDelivery: values.checkbox.indexOf('A')> -1 ? true: false,
                        IsDefaultReceiving: values.checkbox.indexOf('B')> -1? true: false
                    },
                    callBack: {
                        success: res => {
                            this.setState({ btnLoading: false });
                            message.success('保存成功');
                            router.replace({
                                pathname: `/${window.storeId}/store/address`,
                            });
                        },
                        error: res => {
                            this.setState({ btnLoading: false });
                            message.success(res.Msg);
                        }
                    }
                })
            } else {
                this.setState({ btnLoading: false });
            }
        })
    }

    onTextChange = (v) => {
      this.setState({ name: v.target.value  });
  }

  onDetailChange =(v) => {
    this.setState({ detail: v });
  }

    render () {
        const {btnLoading, addressList, initialData} =  this.state;
        // console.log(addressList);
        const formItemLayout = {
            labelCol: {span: 6},
            wrapperCol: { span: 5 },
        };
        const formItemLayout2 = {
            labelCol: {span: 6},
            wrapperCol: { span: 8 },
        };
        const formItemLayout3 = {
            labelCol: {span: 6},
            wrapperCol: { span: 12 },
        };
        const formItemLayout4 = {
            labelCol: {span: 6},
            wrapperCol: { span: 18 },
        };
        const { getFieldDecorator} = this.props.form;
        let options=this.addressTransform(addressList,[],0);
        return (
            <Form className={styles.contentBox} onSubmit={this.handleSubmit}>
                <div className={styles.body}>
                    <Form.Item
                        label="联系人"
                        {...formItemLayout}
                    >{getFieldDecorator('name', {
                        initialValue: initialData.ContractName,
                        rules: [
                            {required: true, message: '联系人必须填写',whitespace: true},
                    ]
                    })(
                      <InputText name="name" onChange={this.onTextChange}  showtotal maxLength={10} />
                    )}
                    </Form.Item>
                    <Form.Item
                        label="联系电话"
                        {...formItemLayout}
                    >{getFieldDecorator('phone', {
                        initialValue: initialData.ContractPhone,
                        rules: [
                            {required: true, message: '联系电话必须填写'},
                            {pattern: /^1[3|4|5|7|8][0-9]{9}$/, message:'请填写正确电话号码'}
                    ],
                    validateTrigger: 'onBlur'
                    })(
                        <Input />
                    )}
                    </Form.Item>
                    <Form.Item
                        label="地区"
                        {...formItemLayout2}
                    >{getFieldDecorator('area', {
                        initialValue: [initialData.ProvId, initialData.CityId, initialData.DistrictId],
                        rules: [
                            {required: true, message: '地区必须填写'}
                    ]
                    })(
                        <Cascader
                            options={options}
                            onChange={this.onChangeCascader}
                            placeholder=""
                        />
                    )}
                    </Form.Item>
                    <Form.Item
                        label="详细地址"
                        {...formItemLayout3}
                    >{getFieldDecorator('detail', {
                        initialValue: initialData.AddressDetail,
                        rules: [
                            {required: true, message: '详细地址必须填写'}
                    ]
                    })(
                      <InputText name="detail" onChange={this.onDetailChange}  showtotal maxLength={60} />
                    )}
                    </Form.Item>

                    {/* <Form.Item
                        {...formItemLayout4}
                        label=" "
                        colon={false}
                    >
                        <div
                            ref ={e => {
                                this.mapContainer = e;
                            }}
                            className={styles.mapContainer}
                        />
                    </Form.Item> */}

                    <Form.Item
                        label="邮政编码"
                        {...formItemLayout}
                    >{getFieldDecorator('zipCode', {
                        initialValue: initialData.ZipCode,
                        rules: [
                            {required: false, message: '邮政编码必须填写'},
                            {pattern: /^[0-9]{6}$/, message:'请填写正确邮编'}
                    ],
                    validateTrigger: 'onBlur'
                    })(
                        <Input />
                    )}
                    </Form.Item>
                    <Form.Item
                        {...formItemLayout}
                        label=" "
                        colon={false}
                        >
                        {getFieldDecorator('checkbox', {
                            initialValue: [initialData.IsDefaultDelivery?'A':'',initialData.IsDefaultReceiving?'B':''],
                        })(
                            <Checkbox.Group style={{ width: "100%" }}>
                                <Checkbox value="A" style={{marginBottom: 16}}>设为默认发货地址</Checkbox>
                                <Checkbox  value="B">设为默认收货地址</Checkbox>
                            </Checkbox.Group>
                        )}
                    </Form.Item>
                    <Form.Item
                        {...formItemLayout}
                        label=" "
                        colon={false}
                    >
                        <Button
                            htmlType="submit"
                            type="primary"
                            loading={btnLoading}
                        >
                            保存
                        </Button>
                    </Form.Item>
                </div>
                {/* <div className="xkd-bottom-actions">
                        <Button className="xkd-mr8">
                             取消
                        </Button>
                            <Button
                            htmlType="submit"
                            type="primary"
                            loading={btnLoading}
                        >
                            保存
                        </Button>
                </div> */}
            </Form>
        )
    }
}

export default Form.create()(EditAddress);
